export default {
	name: "applyDetail",
	setup(props, { emit }) {
		const router = VueRouter.useRouter();
		const route = VueRouter.useRoute();
		const { smartSpeak } = inject('speech'); //语音
		const formData = ref({});
		const bgsx = ref({});
		const originalUser = ref(JSON.parse(localStorage.getItem('user')));
		const approvalProgress = ref({});
		const approvalRecords = ref([]);
		const approvalComment = ref('');
		
		// 获取数据
        const loadData = async () => {
            const id = Number(route.params.id);
            const res = await checkApply({formId: id});
            if(!res?.process?.id) {
                ElMessage.error('无进行中的流程');
                return router.push({name: 'home'});
            }
            // 处理表单数据
            bgsx.value = res.process.formSchema || { fields: {} };
            formData.value = res.formData;
            Object.keys(formData.value).forEach(key => {
                const fieldType = bgsx.value.fields[key]?.type;
                if (fieldType && fieldType == 'multiimage') {
                    try {
                        formData.value[key] = JSON.parse(formData.value[key]) || [];
                    } catch {
                        formData.value[key] = [];
                    }
                }
            });
            // 加载审批状态和记录
            approvalRecords.value = res.process.approvalRecords;
            approvalProgress.value = res.process;
            document.title = approvalProgress.value.formSchema?.formname;
            // 添加状态校验日志
            console.log('流程状态:', approvalProgress.value.status);
            console.log('当前审批步骤:', approvalProgress.value.currentStep);
            console.log('总步骤数:', approvalProgress.value.formSchema?.processConfig?.length);
        };

        // 审批操作
        const handleApproval = _.debounce(async (result) => {
            if (!approvalComment.value && result === 'rejected') {
                ElMessage.warning('拒绝时必须填写审批意见');
                return;
            }
            // 获取当前用户待处理的审批记录（需确保数据加载时包含审批人信息）
            const currentUser = originalUser.value;
            const currentRecord = approvalRecords.value.find(record => 
                record.status === 'pending' && 
                record.approver?.id === originalUser.value.ID
            );
            if (!currentRecord?.id) {
                return ElMessage.error('找不到您需要处理的审批记录');
            }
            await handleapproval({
                recordId: currentRecord.id, // 审批记录ID
                result,
                comment: approvalComment.value
            });
            ElMessage.success('操作成功');
            await loadData();
        }, 300);

		// 工具函数：格式化字段值
		const formatFieldValue = (value, type) => {
			if (type === 'datetime') return dayjs(value).format('YYYY-MM-DD HH:mm');
			if (type === 'checkbox') return value?.join(', ') || '';
			return value?.toString() || '';
		};
		
		const hasPendingApproval = computed(() => {
            return approvalRecords.value.some(record => 
                record.status === 'pending' && 
                record.approver?.id === originalUser.value.ID
            );
        });
		
        // 计算属性：判断流程是否结束
        const isProcessEnded = computed(() => {
            return approvalProgress.value.status === 'rejected' || 
                approvalProgress.value.currentStep > approvalProgress.value.formSchema?.processConfig?.length
        })
    
        // 计算属性：流程结束类型
        const processEndType = computed(() => {
            return approvalProgress.value.status === 'rejected' ? 'danger' : 'success'
        })
    
        // 计算属性：流程结束文本
        const processEndText = computed(() => {
            return approvalProgress.value.status === 'rejected' ? '流程已驳回' : '流程已完成'
        })
    
        // 计算属性：排序后的审批记录
        const sortedApprovalRecords = computed(() => {
            return [...approvalRecords.value].sort((a, b) => new Date(b.CreatedAt) - new Date(a.CreatedAt))
        })
    
        // 步骤状态判断
        const getStepStatus = (stepNumber) => {
            if (approvalProgress.value.status === 'rejected') {
                return 'error' // 被驳回的流程全部标记为错误
            }
    
            if (stepNumber < approvalProgress.value.currentStep) {
                return 'success'
            }
            
            if (stepNumber === approvalProgress.value.currentStep) {
                return isProcessEnded.value ? 'success' : 'process'
            }
            
            return 'wait'
        }
		
        onMounted(async() => {
			await loadData();
		});
		
        watch(() => route.params.id, async (newId, oldId) => {
            if (newId !== oldId) {
                await loadData();
            }
        });

		return {
			isAuditor: originalUser.value.Role === 'shy',
			bgsx,
			formData,
			approvalProgress,
			approvalRecords,
			approvalComment,
			handleApproval,
			formatFieldValue,
			hasPendingApproval,
			zt: {
                pending:    '待审批',
                approved:   '已通过', 
                rejected:   '已驳回',
                processing: '审批中' 
            },
            sortedApprovalRecords,
            isProcessEnded,
            processEndType,
            processEndText,
            getStepStatus
		};
		
	},
	
	template: `
	<div>
		<div class="header row">
			<div class="col-lg-2 col-md-0">&nbsp;</div>
			<div class="col-lg-10 col-md-12">
				<img class="icon-logo" src="/pc_static/logo.png" />
			</div>
		</div>
		<div class="cen-form2" v-if="bgsx?.id && Object.keys(formData).length" style="margin-top:20px;">
			<el-card style="width: 100%; max-width: 1200px;">
				<!-- 头部：表单名称 + 审批进度 -->
				<template #header>
					<div style="text-align:center;">
						<h3>{{bgsx?.formname}}</h3>
						<div v-if="approvalProgress" class="approval-progress">
							<el-steps :active="approvalProgress.currentStep" align-center>
                                <el-step v-for="(step, index) in approvalProgress.steps" 
                                    :key="index"
                                    :title="'步骤'+ (index + 1)"
                                    :description="step.Approver?.Name || '未知' + '|' + zt[step.status]"
                                    :status="step.status === 'approved' ? 'success' : step.status === 'rejected' ? 'error' : 'process'">
                                </el-step>
							</el-steps>
						</div>
					</div>
				</template>

				<!-- 表单内容（只读模式） -->
				<div class="form-content">
					<el-descriptions border :column="2">
						<el-descriptions-item v-for="(field, k) in bgsx.fields" :key="k" :label="field.name">
                            <template v-if="!['submit', 'audit', 'cjz', 'id', 'created_at','updated_at','query_count'].includes(field.type)">
                            	<!-- 通用只读展示 -->
                            	<span v-if="!['image', 'multiimage'].includes(field.type)">
                            		{{ formatFieldValue(formData[k], field.type) }}
                            	</span>
                            
                            	<!-- 图片展示 -->
                            	<div v-else class="image-preview">
                            		<el-image
                            			v-for="(url, index) in (Array.isArray(formData[k]) ? formData[k] : [formData[k]])"
                            			:key="index" :src="url" fit="cover" class="preview-image">
                            		</el-image>
                            	</div>
                            </template>
						</el-descriptions-item>
					</el-descriptions>
				</div>

				<!-- 审批操作区（仅审核员可见） -->
				<div v-if="isAuditor && hasPendingApproval" class="approval-action">
					<el-input v-model="approvalComment" type="textarea" placeholder="请输入审批意见" :rows="3" style="margin: 20px 0;"></el-input>
					<div style="text-align: center;">
						<el-button type="success" @click="handleApproval('approved')">通过</el-button>
						<el-button type="danger" @click="handleApproval('rejected')">拒绝</el-button>
					</div>
				</div>

				<!-- 审批记录 -->
				<div v-if="approvalRecords?.length" style="margin-top: 20px;">
					<div style="text-align:center;"><h3>审批记录</h3></div>
                    <!-- 步骤显示部分 -->
                    <el-steps :active="approvalProgress.currentStep + 1" align-center>
                        <el-step title="发起人" :description="approvalProgress.initiator?.name || '申请人'" status="success"/>
                        <el-step v-for="(step, index) in approvalProgress.formSchema?.processConfig" :key="index" :title="'步骤' + (index + 1)" :description="step?.approverName || '未知审批人'" :status="getStepStatus(index + 1)"/>
                    </el-steps>
					
					<el-timeline style="margin: 20px;">
					    <!-- 发起人提交记录 -->
                        <el-timeline-item :timestamp="$validators.formatDate(formData?.created_at)" placement="top">
                            <el-tag type="success">发起</el-tag>
                            <span class="approver">{{ approvalProgress.initiator?.name }}</span>
                        </el-timeline-item>
                        <el-timeline-item v-for="record in sortedApprovalRecords" :key="record.id" placement="top" :timestamp="record.status === 'pending' ? '' : $validators.formatDate(record.CreatedAt)">
							<div class="record-card" :class="record.status">
								<div class="record-header">
									<div class="status-wrapper">
										<el-tag size="small" :type="record.status === 'approved' ? 'success' : 'danger'" effect="dark"
											class="status-tag">
											<el-icon v-if="record.status == 'approved'"><SuccessFilled /></el-icon>
                                            <el-icon v-else><CircleCloseFilled /></el-icon>
											{{ zt[record.status] }}
										</el-tag>
										<span class="approver-name">
											<el-icon><User /></el-icon>
											{{ record.approver?.name || '未知审批人' }}
										</span>
									</div>
									<span class="step-info"><el-icon><ChatLineRound /></el-icon>步骤 {{ record.step }}</span>
								</div>

								<div class="comment-box" v-if="record.comment">
									<div class="comment-header">
										<el-icon><ChatLineRound /></el-icon>
										<span>审批意见</span>
									</div>
									<p class="comment-content">{{ record.comment }}</p>
								</div>
							</div>
						</el-timeline-item>
                        <!-- 流程结束标记 -->
                        <el-timeline-item v-if="isProcessEnded">
                            <el-card>
                                <template #header>
                                    <div class="record-header">
                                        <el-tag :type="processEndType">
                                            {{ processEndText }}
                                        </el-tag>
                                    </div>
                                </template>
                            </el-card>
                        </el-timeline-item>
					</el-timeline>
				</div>

			</el-card>
		</div>
	</div>

`
}